package com.googlecode.technorati4j.util;

import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.jdom.Element;

public final class XMLUtils {

    public static String getNodeAsString(Element e, String path) {
        if (path.contains(Constants.XML_NODE_SEPARATOR)) {
            String[] nodes = path.split(Constants.XML_NODE_SEPARATOR);

            for (int i = 0; i < nodes.length - 1; i++) {
                e = e.getChild(nodes[i]);

                if (e == null) {
                    return null;
                }

                path = nodes[i + 1];
            }
        }

        return e == null ? null : e.getChildTextTrim(path);
    }

    public static Integer getNodeAsInteger(Element e, String path) {
        String s = getNodeAsString(e, path);
        return StringUtils.toInteger(s);
    }

    public static Double getNodeAsDouble(Element e, String path) {
        String s = getNodeAsString(e, path);
        return StringUtils.toDouble(s);
    }

    public static Date getNodeAsDate(Element e, String path, String format) {
        String s = getNodeAsString(e, path);
        return StringUtils.toDate(s, format);
    }

    @SuppressWarnings("unchecked")
    public static List<Element> getNodeAsList(Element e, String path) {
        if (path.contains(Constants.XML_NODE_SEPARATOR)) {
            String[] nodes = path.split(Constants.XML_NODE_SEPARATOR);

            for (int i = 0; i < nodes.length - 1; i++) {
                e = e.getChild(nodes[i]);

                if (e == null) {
                    return Collections.emptyList();
                }

                path = nodes[i + 1];
            }
        }

        return e == null ? null : e.getChildren(path);
    }
}
